package com.common.help.test15;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class NIOServer {
	
	private ByteBuffer send = ByteBuffer.allocate(1024);
	private ByteBuffer recive = ByteBuffer.allocate(1024);
	private int port ;
	private ServerSocketChannel server;
	private Selector selector;

	private static Map<SelectionKey,String> map = new HashMap<>();
	public NIOServer(int port) throws IOException{
		
		this.port = port;
		server = ServerSocketChannel.open();
		server.socket().bind(new InetSocketAddress(this.port));
		server.configureBlocking(false);
		
		selector = Selector.open();
		
		server.register(selector, SelectionKey.OP_ACCEPT);
		System.out.println("NIO服务端已启动 端口是=======>:"+this.port);
	}
	
	public static void main(String[] args) throws IOException {
		new NIOServer(8080).listener();
	}

	private void listener() throws IOException {
		
		while(true){
			//看selector里是否有key
			int count = selector.select();
			if(count == 0){
				continue;
			}
			Set<SelectionKey> keys = selector.selectedKeys();
			Iterator<SelectionKey> iterator = keys.iterator();
			while(iterator.hasNext()){
				SelectionKey key = iterator.next();
				process(key);//执行key
				iterator.remove();
			}
			
		}
	}

	private void process(SelectionKey key) throws IOException {
		if(key.isAcceptable()){
			SocketChannel client = server.accept();
			client.configureBlocking(false);
			client.register(selector, SelectionKey.OP_READ);
		}else if(key.isReadable()){
			System.out.println(key);
			recive.clear();
			SocketChannel client = (SocketChannel)key.channel();
			int len = client.read(recive);
			if(len > 0){
				String ss = new String(recive.array(),0,len);
				map.put(key, ss);
				System.out.println("收到客户端的信息 :"+ss);
			}
			recive.flip();
			client.register(selector, SelectionKey.OP_WRITE);
		}else if(key.isWritable()){
			System.out.println(key);
			if(!map.containsKey(key)){return;}
			String name = (String)map.get(key);
			send.clear();
			SocketChannel client = (SocketChannel)key.channel();
			send.put(("亲爱的: "+name+" 我收到消息 做了处理了").getBytes());
			send.flip();
			client.write(send);
			client.register(selector, SelectionKey.OP_READ);
		}
	}
}
